package com.numberone.master.modules.Interfaces.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.modules.card.entity.CardRechargeFlow;
import com.numberone.master.modules.card.service.CardAmountService;
import com.numberone.master.modules.card.service.CardRechargeFlowService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付和回调相关
 */
@Controller
@RequestMapping(value = "${adminPath}/aliPay")
public class AliPayController {
	

	@Autowired
	private CardAmountService cardAmountService;
	@Autowired
	CardRechargeFlowService cardRechargeFlowService;
	
	//初始化参数 不然signVerified会验证失败
	static {
		Configs.init("zfbinfo.properties");
	}

	private final static Logger log = Logger.getLogger(AliPayController.class);

	/**
	 * 支付宝订单回调
	 * 
	 * @param requests
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "callBack", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	public void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("支付宝付款异步通知==================================");
		String message = "success";
		Map<String, String> params = new HashMap<String, String>();
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		// 验证签名
		boolean signVerified = false;
		try {
			signVerified = AlipaySignature.rsaCheckV1(params, Configs.getAlipayPublicKey(), "UTF-8",Configs.getSignType());
			//signVerified = AlipaySignature.rsaCheckV1(params, Configs.getAlipayPublicKey(), "UTF-8");
		} catch (AlipayApiException e) {
			e.printStackTrace();
			message = "failed";
		}
		if (signVerified) {
			log.info("验证签名成功！");
			// 若参数中的appid和填入的appid不相同，则为异常通知
			if (!Configs.getAppid().equals(params.get("app_id"))) {
				log.info("与付款时的appid不同，此为异常通知，应忽略！");
				message = "failed";
			} else {
				String outtradeno = params.get("out_trade_no");
				//订单金额
				String totalAmount = params.get("total_amount");
				//付款时间
				String gmtPayment = params.get("gmt_payment");
				System.out.println("订单金额====================="+outtradeno);
				System.out.println("付款时间====================="+totalAmount);
				System.out.println("订单号====================="+gmtPayment);
				log.info(outtradeno + "号订单回调通知==============================");
				// 在数据库中查找订单号对应的订单，并将其金额与数据库中的金额对比，若对不上，也为异常通知
				String status = params.get("trade_status");
				if (status.equals("WAIT_BUYER_PAY")) { // 如果状态是正在等待用户付款
					
				} else if (status.equals("TRADE_CLOSED")) { // 如果状态是未付款交易超时关闭，或支付完成后全额退款
					cardRechargeFlowService.updatePayState(3,outtradeno);
				} else if (status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISHED")) { // 如果状态是已经支付成功
					CardRechargeFlow cardRechargeFlow = cardRechargeFlowService.selectCardRechargeFlow(outtradeno);
					if(cardRechargeFlow == null){//添加异常订单
						CardRechargeFlow c = new CardRechargeFlow();
						c.setIccid("");
						c.setAmount(new Double(totalAmount));
						c.setState(4);
						c.setOrderId(outtradeno);
						c.setCreateTime(new Date());
						c.setPayTime(DateUtils.strToDateLong(gmtPayment));
						cardRechargeFlowService.insert(c);
					}else{
						//成功订单并且是等待付款的订单信息修改状态
						if(cardRechargeFlow.getState() == 0){
							int flowType = cardRechargeFlow.getFlowType();
							cardRechargeFlowService.updatePayState(1,outtradeno);
							if(flowType == 0){//余额充值,添加个人账户余额
								cardAmountService.addAmount(cardRechargeFlow.getIccid(),new Double(totalAmount));
							}
						}
					}
				} else {
					// weixinpayBack.updateAccOrder(outtradeno);
				}
				log.info(outtradeno + "订单的状态已经修改为===========" + status);
			}
		} else { // 如果验证签名没有通过
			message = "failed";
			log.info("验证签名失败=====================");
		}
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(message.getBytes());
		out.flush();
		out.close();
	}
}